<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="昵称" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          placeholder="请输入昵称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
     <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
      <el-form-item class="fr">
        <el-button  icon="el-icon-price-tag" size="small" type="success" @click="$refs.wxUserTagsEditor.show(true)">标签管理</el-button>
        <el-button  icon="el-icon-sort" size="small" type="success" @click="syncWxUsers()">同步粉丝</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="$refs.wxUserTagging.init('tagging')"
          :disabled="multiple"
          v-hasPermi="['wx:wxuser:edit']"
        >绑定标签</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          @click="$refs.wxUserTagging.init('untagging')"
          :disabled="multiple"
          v-hasPermi="['wx:wxuser:edit']"
        >解绑标签</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wx:wxuser:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wx:wxuser:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="wxuserList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="appid" align="center" prop="appid" width="160"/>
      <el-table-column prop="openid" align="center" label="openid" :show-overflow-tooltip="true"/>
      <el-table-column prop="nickname" align="center" label="昵称" />
      <el-table-column prop="sex" align="center" label="性别" :formatter="sexFormat" />
      <el-table-column prop="city" align="center" label="城市" />
      <el-table-column prop="headimgurl" align="center" label="头像">
        <img class="headimg" slot-scope="scope" v-if="scope.row.headimgurl" :src="scope.row.headimgurl" />
      </el-table-column>
      <el-table-column prop="tagidList" align="center" label="标签" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-for="tagid in scope.row.tagidList" :key="tagid">{{getTagName(tagid)}} </span>
        </template>
      </el-table-column>
      <el-table-column prop="subscribeTime" align="center" label="订阅时间">
        <template slot-scope="scope">{{$moment(scope.row.subscribeTime).calendar()}}</template>
      </el-table-column>
      <el-table-column prop="qrSceneStr" align="center" label="场景值">
      </el-table-column>
      <el-table-column prop="subscribe" align="center" label="是否关注">
        <span slot-scope="scope">{{scope.row.subscribe?"是":"否"}}</span>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">

          <el-button
            size="mini"
            circle type="danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wx:wxuser:remove']"
          />
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->

    <wx-user-tags-manager ref="wxUserTagsEditor" :visible="showWxUserTagsEditor" @close="showWxUserTagsEditor=false"></wx-user-tags-manager>
    <wx-user-tagging ref="wxUserTagging" :wxUsers="dataListSelections"></wx-user-tagging>
  </div>
</template>

<script>
import { listWxuser, getWxuser, delWxuser, addWxuser, updateWxuser, exportWxuser,syncWxUsers } from "@/api/wx/wxuser";
import WxUserTagsManager from '@/components/wx-user-tags-manager'
import WxUserTagging from './wx-user-tagging'
import { mapState } from 'vuex'

export default {
  name: "Wxuser",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      openids:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 参数表格数据
      wxuserList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 类型数据字典
      typeOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        paramName: undefined,
        paramKey: undefined,
        paramType: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        paramName: [
          { required: true, message: "参数名称不能为空", trigger: "blur" }
        ],
        paramKey: [
          { required: true, message: "参数键名不能为空", trigger: "blur" }
        ],
        paramValue: [
          { required: true, message: "参数键值不能为空", trigger: "blur" }
        ]
      },
      dataListSelections: [],
      showWxUserTagsEditor:false
    };
  },
  components: {
    WxUserTagsManager,WxUserTagging
  },
  computed: mapState({
    wxUserTags:state=>state.wxUserTags.tags
  }),
  created() {
    this.getList();
    this.getDicts("sys_yes_no").then(response => {
      this.typeOptions = response.data;
    });
  },
  methods: {
    /** 查询参数列表 */
    getList() {
      this.loading = true;
      listWxuser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.wxuserList = response.data.list;
          this.total = response.data.total;
          this.loading = false;
        }
      );
    },
    // 参数系统内置字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.paramType);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        paramName: undefined,
        paramKey: undefined,
        paramValue: undefined,
        paramType: "Y",
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加参数";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
      this.dataListSelections = selection
      this.openids = selection.map(item => item.openid)
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getWxuser(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改参数";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            updateWxuser(this.form.id,this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.message);
              }
            });
          } else {
            addWxuser(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.message);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.openid || this.openids;
      this.$confirm('是否确认删除参数编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delWxuser(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有参数数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return exportWxuser(queryParams);
      }).then(response => {
        this.fileDownload(response.data, "系统参数.xlsx");
      }).catch(function() {});
    },
    sexFormat(row, column, cellValue) {
      let sexType = {
        0: '未知',
        1: '男',
        2: '女'
      }
      return sexType[cellValue];
    },
    getTagName(tagid){
      let tag = this.wxUserTags.find(item=>item.id==tagid)
      return tag?tag.name : "?"
    },
    syncWxUsers(){
      // this.$http({
      //   url: this.$http.adornUrl('/manage/wxUser/syncWxUsers'),
      //   method: 'post',
      // }).then(({ data }) => {
      //   if (data && data.code === 200) {
      //     this.$message({
      //       message: '同步任务已建立，请稍候刷新查看列表',
      //       type: 'success',
      //       duration: 1500
      //     })
      //   } else {
      //     this.$message.error(data.msg)
      //   }
      // })

      syncWxUsers().then(response => {
        if (response.code === 200) {
          this.msgSuccess("'同步任务已建立，请稍候刷新查看列表");
          this.getList();
        } else {
          this.msgError(response.message);
        }
      });
    },
  }

};
</script>
<style scoped>
.headimg{
  width: 40px;
  height: 40px;
  border-radius: 8px;
}
</style>
